#!/usr/bin/env python
# -*- coding: utf-8 -*-
from typing import TypeVar

from sqlalchemy import or_, and_
from sqlalchemy.orm import Session

from app.models import User
from pydantic import BaseModel

from app.dao.base_dao import BaseDao
from app.db.base_class import Base
from app.models.bar import Bar
from app.models.constant import Constant
from app.models.favorite import Favorite
from app.models.instrument import Instrument
from app.models.strategy import Strategy
from app.models.user_setting import UserSetting
from app.schemas.bar import CandlestickQuery
from app.schemas.favorite import FavoriteQuery
from app.schemas.instrument import PickableQuery


class FavoriteDao(BaseDao[Favorite]):
    def __init__(self):
        super(FavoriteDao, self).__init__()
        self.modelClass = Favorite
        self.id = Favorite.id

    def selectUserFavorites(self, db: Session, queryWrapper: CandlestickQuery):
        result = db.query(Instrument.id, Favorite.id.label('favoriteId'), Instrument.name, Instrument.symbol, Bar.close, Bar.open, Bar.low, Bar.high,
                          Bar.volume, Bar.amount, Bar.barDate, Bar.preClose) \
            .select_from(Favorite) \
            .outerjoin(Instrument, Favorite.instrumentId == Instrument.id) \
            .outerjoin(Bar, and_(Favorite.instrumentId == Bar.instrumentId,
                       Bar.barDate == queryWrapper.barDate,
                       Bar.frequency == queryWrapper.frequency,
                       Bar.adjustFlag == queryWrapper.adjust)) \
            .filter(
            Favorite.userId == queryWrapper.userId,
            Instrument.marketType == queryWrapper.marketType) \
            .order_by(Instrument.symbol.asc()) \
            .all()
        return result


favoriteDao = FavoriteDao()
